import json
import aiohttp

import httplib2
from urllib.parse import urlencode

# 调用查询网天气接口
def chaxun_weather(code: str) -> bytes:
    params = urlencode({'code': code, 'type': '2', 'callback': 'find'})
    url = 'http://api.ip138.com/weather/?' + params
    headers = {"token": "535ea54ad49500915ecabe7c8c9a9727"}
    http = httplib2.Http()
    response, content = http.request(url, 'GET', headers=headers)
    return content

# 调用图灵机器人接口
async def tuling_weather(text: str,url: str,apikey: str):
    if not (text, url, apikey):
        return None

    data = {
        'key': apikey,
        'info': text,
        'userid': '1395363625'
    }
    # 使用aiohttp发送请求
    try:
        async with aiohttp.ClientSession() as sess:
            async with sess.post(url, json=data) as response:
                if response.status != 200:
                    return None
                resp_data = json.loads(await response.text())
                if resp_data['text']:
                    result = resp_data['text']
                    return result
    except(aiohttp.ClientError, json.JSONDecodeError):
        return None

